package cn.ylg.com.baisibudeijie.lib;

import android.content.Context;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;

import java.util.Map;

import cn.ylg.com.baisibudeijie.lib.callback.ObjectCallback;
import cn.ylg.com.baisibudeijie.lib.future.HttpFuture;

/**
 * Created by MyPC on 2016/10/21.
 */
public class HttpManager {
    private static  HttpManager instance;
    private Context context;
    private HttpManager(Context context){
        this.context = context;
    }
    public static  HttpManager getInstance(Context context){
        if (instance == null){
            synchronized (HttpManager.class){
                if (instance==null){
                    instance = new HttpManager(context);
                }
            }
        }
        return instance;
    }

    public HttpFuture sendRequest(String url, Map<String, String> headers, Map<String,String> paramters,final  ObjectCallback callback){
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams reparams = new RequestParams();
        // 请求消息头
        if (headers != null) {
            for (Map.Entry<String, String> me : headers.entrySet()) {
                client.addHeader(me.getKey(), me.getValue());
            }
        }
        //将HashMap封装到RequestParams 中
        if (paramters!=null){
            for (Map.Entry<String,String> me:paramters.entrySet()) {
                reparams.put(me.getKey(),me.getValue());
            }
        }
        // 调用post方法访问网络
        RequestHandle handle = client.post(context, url, reparams,
                new TextHttpResponseHandler() {

                    @SuppressWarnings("unchecked")
                    @Override
                    public void onSuccess(int statusCode, Header[] headers,
                                          String responseString) {
                        Log.d("success", responseString + "");

                        JsonParser parser = new JsonParser();
                        JsonElement element = parser.parse(responseString);
                        JsonObject root = element.getAsJsonObject();

                        JsonPrimitive flagJson = root
                                .getAsJsonPrimitive("flag");
                        boolean flag = flagJson.getAsBoolean();

                        if (flag) {
                            JsonObject dataObject = root
                                    .getAsJsonObject("data");
                            if (dataObject != null) {
                                if (callback != null) {
                                    @SuppressWarnings("unchecked")
                                    Object obj = new Gson().fromJson(
                                            dataObject, callback.getDataClass());
                                    callback.onSuccess(obj);
                                }
                            }
                        } else {
                            JsonPrimitive errorCodeJson = root
                                    .getAsJsonPrimitive("errorCode");
                            JsonPrimitive errorStringJson = root
                                    .getAsJsonPrimitive("errorString");

                            Log.d("", errorCodeJson.getAsInt() + " : "
                                    + errorStringJson.getAsString());

                            if (callback != null) {
                                callback.onFailure(errorCodeJson.getAsInt(),
                                        errorStringJson.getAsString());
                            }
                        }
                    }

                    @Override
                    public void onFailure(int statusCode, Header[] headers,
                                          String responseString, Throwable throwable) {
                        Log.d("error",
                                responseString + " : " + throwable.getMessage());

                        if (callback != null) {
                            callback.onFailure(HMError.ERROR_SERVER, "服务器连接问题");
                        }

                    }
                });
        return new HttpFuture(handle);
    }

}
